import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_chip/bean/Goods.dart';
import 'package:flutter_chip/config/Api.dart';
import 'package:flutter_chip/config/Comm.dart';
import 'package:flutter_chip/config/Http.dart';
import 'package:flutter_chip/config/Routers.dart';
import 'package:flutter_chip/utils/toast_utils.dart';
import 'package:flutter_chip/widget/widget_comm.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

///发布的商品

class MyGoodsPage extends StatefulWidget {
  final userId;
  final bool isSelf;

  const MyGoodsPage({Key key, this.userId, this.isSelf = false})
      : super(key: key);

  @override
  _MyGoodsPageState createState() => _MyGoodsPageState();
}

class _MyGoodsPageState extends State<MyGoodsPage> {
  //数据集合
  var _item = [];
  EasyRefreshController _easyRefreshController = EasyRefreshController();
  int childCount = 0;

  @override
  void initState() {
    super.initState();
    _getGoods();
  }

  @override
  Widget build(BuildContext context) {
    return EasyRefresh.custom(
      enableControlFinishRefresh: true,
      header: CommWidget.commHeader(),
      emptyWidget: childCount == 0 ? CommWidget.nullWidget() : null,
      controller: _easyRefreshController,
      enableControlFinishLoad: true,
      slivers: <Widget>[
        SliverList(
          delegate: SliverChildBuilderDelegate((context, index) {
            return Column(
              children: <Widget>[
                GestureDetector(
                  child: _itemView(context, index),
                  onTap: () {
                    Goods goods = _item[index];
                    String url =
                        '${Routers.PAGE_GOOD_INFO}?goodsId=${goods.goodsId}';
                    Routers.router.navigateTo(context, url,
                        transition: TransitionType.inFromRight);
                  },
                ),
                Container(height: 8, color: Theme.of(context).selectedRowColor),
              ],
            );
          }, childCount: childCount),
        )
      ],
      onRefresh: () => _getGoods(),
    );
  }

  ///列表Item
  _itemView(BuildContext context, int index) {
    Goods goods = _item[index];
    String statusPic;
    if (goods.status == 0) {
      statusPic = Comm.IMG_SHZ;
    } else if (goods.status == 1) {
      statusPic = Comm.IMG_YFB;
    } else if (goods.status == 2) {
      statusPic = Comm.IMG_YBH;
    } else {
      statusPic = Comm.IMG_YXJ;
    }
    return Container(
      color: Theme.of(context).cardColor,
      padding: EdgeInsets.only(left: 10, right: 10, top: 4, bottom: 4),
      child: Stack(
        children: <Widget>[
          Column(
            children: <Widget>[
              Row(
                  mainAxisSize: MainAxisSize.max,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    Expanded(flex: 1, child: _picWidget(goods)),
                    SizedBox(width: 6),
                    Expanded(flex: 2, child: _goodsWidget(goods))
                  ]),
              Offstage(offstage: !widget.isSelf, child: Divider()),
              Offstage(offstage: !widget.isSelf, child: _handlerWidget(goods)),
              SizedBox(height: 6),
            ],
          ),
          Offstage(
            offstage: !widget.isSelf,
            child: Container(
              child: Align(
                alignment: Alignment.bottomLeft,
                child: Image.asset(
                  statusPic,
                  width: 64,
                  height: 64,
                ),
              ),
              margin: EdgeInsets.only(top: 60, left: 40),
            ),
          ),
        ],
      ),
    );
  }

  ///商品图片
  Widget _picWidget(Goods goods) {
    return Container(
      width: 120,
      height: 80,
      decoration: BoxDecoration(
        color: Color(0x7f000000),
        borderRadius: BorderRadius.circular(4),
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(4),
        child: CachedNetworkImage(
          imageUrl: Api.getUrl(goods.goodsImg.split(",")[0]),
          fit: BoxFit.fitWidth,
          errorWidget: (context, url, error) => CommWidget.imgError(),
        ),
      ),
    );
  }

  ///商品信息
  Widget _goodsWidget(Goods goods) {
    return Column(
        mainAxisSize: MainAxisSize.max,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
            goods.goodsName,
            style: TextStyle(fontSize: 16),
            softWrap: false,
            overflow: TextOverflow.ellipsis,
          ),
          Text(
            goods.goodsInfo,
            maxLines: 2,
            softWrap: false,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(color: Colors.grey),
          ),
          _disPriceWidget(goods),
        ]);
  }

  ///原价显示
  Widget _disPriceWidget(Goods goods) {
    bool showPrice = null != goods && null != goods.price && goods.price > 0;
    return Row(crossAxisAlignment: CrossAxisAlignment.end, children: <Widget>[
      Offstage(
        offstage: !showPrice,
        child: Text(
          '￥',
          style: TextStyle(
            color: Color(0xffFA4344),
            fontSize: 12,
            fontWeight: FontWeight.w400,
          ),
        ),
      ),
      Text(
        '${showPrice ? goods.price : "免费"}',
        style: TextStyle(
          color: Color(0xffFA4344),
          fontSize: showPrice ? 18 : 16,
          fontWeight: showPrice ? FontWeight.w600 : FontWeight.w500,
        ),
      ),
      Expanded(child: Container()),
      Text(
        '卖出${goods.buyNum}件',
        style: TextStyle(
          color: Color(0xffbbbbbb),
          fontSize: 12,
        ),
      )
    ]);
  }

  ///操作按钮
  Widget _handlerWidget(Goods goods) {
    return Row(
      children: <Widget>[
        Offstage(
          offstage: goods.status != 2,
          child: Container(
            child: Text(
              "驳回原因：${goods.reason ?? ""}",
              style: TextStyle(
                fontSize: 12,
                color: Colors.grey,
              ),
            ),
          ),
        ),
        Expanded(flex: 1, child: Container()),
        Offstage(
          offstage: goods.status != 0 && goods.status != 2 && goods.status != 3,
          child: GestureDetector(
            child: Container(
              padding: EdgeInsets.only(left: 8, right: 8),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(6),
                border: Border.all(color: Colors.blue, width: 1),
              ),
              height: 28,
              alignment: Alignment.center,
              child: Text(
                "编辑",
                style: TextStyle(color: Colors.blue),
              ),
            ),
            onTap: () {
              Routers.router.navigateTo(
                  context, "${Routers.PAGE_ADDGOODS}?goodsId=${goods.goodsId}",
                  transition: TransitionType.inFromRight);
            },
          ),
        ),
        Offstage(
            offstage:
                goods.status != 0 && goods.status != 2 && goods.status != 3,
            child: SizedBox(width: 10)),
        Offstage(
          offstage: goods.status != 1,
          child: GestureDetector(
            child: Container(
              padding: EdgeInsets.only(left: 8, right: 8),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(6),
                border: Border.all(color: Colors.blue, width: 1),
              ),
              height: 28,
              alignment: Alignment.center,
              child: Text(
                "下架",
                style: TextStyle(color: Colors.blue),
              ),
            ),
            onTap: () {
              showMsgDialog(context, goods.goodsId, "04");
            },
          ),
        ),
        Offstage(offstage: goods.status != 1, child: SizedBox(width: 10)),
        Offstage(
          offstage: goods.status != 3,
          child: GestureDetector(
            child: Container(
              padding: EdgeInsets.only(left: 8, right: 8),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(6),
                border: Border.all(color: Colors.blue, width: 1),
              ),
              height: 28,
              alignment: Alignment.center,
              child: Text(
                "上架",
                style: TextStyle(color: Colors.blue),
              ),
            ),
            onTap: () {
              showMsgDialog(context, goods.goodsId, "03");
            },
          ),
        ),
        Offstage(offstage: goods.status != 3, child: SizedBox(width: 10)),
        Offstage(
          offstage: goods.status == 1,
          child: GestureDetector(
            child: Container(
              padding: EdgeInsets.only(left: 8, right: 8),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(6),
                border: Border.all(color: Colors.blue, width: 1),
              ),
              height: 28,
              alignment: Alignment.center,
              child: Text(
                "删除",
                style: TextStyle(color: Colors.blue),
              ),
            ),
            onTap: () {
              showMsgDialog(context, goods.goodsId, "02");
            },
          ),
        ),
      ],
    );
  }

  ///信息提示对话框
  void showMsgDialog(BuildContext context, String goodsId, String handle) {
    String msg;
    if ("02" == handle) {
      msg = "您确定要删除吗？";
    } else if ("03" == handle) {
      msg = "您确定要重新上架吗？";
    } else {
      msg = "您确定要下架吗？";
    }
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text("提示"),
            content: Text(msg, style: TextStyle(fontSize: 16)),
            actions: <Widget>[
              FlatButton(
                child: Text("取消"),
                onPressed: () {
                  Navigator.pop(context);
                },
              ),
              FlatButton(
                child: Text("确定"),
                onPressed: () {
                  Navigator.pop(context);
                  _update(goodsId, handle);
                },
              ),
            ],
          );
        });
  }

  ///获取列表
  Future _getGoods() async {
    Map<String, String> params = Map();
    params['userId'] = "${widget.userId}";
    Http.get(Api.URL_GOODSLIST, params: params, successCallBack: (data) {
      List list = json.decode(data).map((m) => Goods.fromJson(m)).toList();
      _item.clear();
      _easyRefreshController.finishRefresh();
      setState(() {
        _item.addAll(list);
        childCount = _item.length;
      });
    }, errorCallBack: (msg) {
      _easyRefreshController.finishRefresh();
    });
  }

  ///编辑
  void _update(String goodsId, String handle) {
    Map<String, String> params = Map();
    params["goodsId"] = goodsId;
    params["handle"] = handle;
    Http.post(Api.URL_GOODSUPDATE, params: params, successCallBack: (data) {
      _getGoods();
    }, errorCallBack: (error) {
      Toast.show(error);
    });
  }
}
